package cn.bdqn.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bdqn.entity.Invitation;
import cn.bdqn.entity.Reply;
import cn.bdqn.service.InvitationService;
import cn.bdqn.service.ReplyService;
import cn.bdqn.util.Constants;
import cn.bdqn.util.Page;

import com.alibaba.fastjson.JSON;

@Controller
@RequestMapping("/invitation")
public class InvitationController {

	@Resource
	private InvitationService invitationService;
	@Resource
	private ReplyService replyService;
	
	@RequestMapping("/invitationList")
	public String getInvitationPageList(String title,Integer pageIndex,Model model){
		
		List<Invitation> Invitations = null;
		if(title != null && title != null){
			Invitations = invitationService.getInvitationListByTitle(title);
			model.addAttribute("title", title);
		}else{
			Invitations = invitationService.getInvitationList();
		}
		if(pageIndex == null || pageIndex <= 0){
			pageIndex = 1;
		}
		
		Page page = new Page(Constants.pageSize,Invitations.size(),pageIndex);
		
		List<Invitation> invitationList = invitationService.getInvitationPageList(title, page);
		model.addAttribute("invitationList", invitationList);
		model.addAttribute("page", page);
		
		return "invitationList";
	}
	
	@RequestMapping("/getReplyById")
	public String getReplyById(Integer id,Integer pageIndex,Model model){
		
		if(pageIndex ==null || pageIndex <= 0){
			pageIndex = 1;
		}
		List<Reply> replys = replyService.getReplyListById(id);
		Page page = new Page(Constants.pageSize,replys.size(),pageIndex);
		
		List<Reply> replyList = replyService.getReplyPageListById(id, page);
		model.addAttribute("replyList", replyList);
		model.addAttribute("page", page);
		model.addAttribute("id", id);
		
		return "replyList";
	}
	
	@RequestMapping("/addReplyByIdInfo")
	public String addReplyByIdInfo(Integer id,Model model){
		model.addAttribute("id", id);
		return "addReply";
	}
	
	@RequestMapping("/addReplyById")
	public String addReplyById(Reply reply){
		reply.setCreateDate(new Date());
		replyService.addReplyById(reply);
		return "redirect:/invitation/getReplyById?id=" + reply.getInvId();
	}
	
	@ResponseBody
	@RequestMapping("/delInvitation")
	public Object delInvitation(Integer id){
		Map map = new HashMap<String,Object>();
		if(replyService.delReply(id) == 1){
			map.put("result", "y");
		}else{
			map.put("result", "n");
		}
		
		return JSON.toJSONString(map);
	}
	
}
